#include "Engine.h"

using namespace sf;

sf::RenderWindow* pApp;

jfw::Engine::Engine()
{}

/*bool jfw::Engine::LoadSettings(std::string m_sFilename,std::string m_sSeparator="=")
{
    std::fstream ConfigFile;
    ConfigFile.open(m_sFilename.c_str(), std::ios::in);
    if(ConfigFile.is_open())
    {
        std::string tmp_sLine="";
        int tmp_iSeparatorAt=0;

        while(ConfigFile.good())
            {
                getline(ConfigFile,tmp_sLine);

                tmp_iSeparatorAt = tmp_sLine.find(m_sSeparator);

                Settings.insert(std::pair<std::string,std::string>(tmp_sLine.substr(0,tmp_iSeparatorAt),
                                                                      tmp_sLine.substr(tmp_iSeparatorAt,tmp_sLine.length()-tmp_iSeparatorAt)));

                tmp_sLine="";
                tmp_iSeparatorAt=0;
            }
        ConfigFile.close();
        return true;
    }
    else
    {
        return false;
    }
}
*/
/*bool jfw::Engine::Open()
{

}*/

bool jfw::Engine::Open(int iWidth=1024, int iHeight=768, int iBits=32, const char* sTitle="", float m_fTimeStep=0.2f)
{
    pApp = new sf::RenderWindow();
    //App.Create(VideoMode(iWidth, iHeight, iBits), sTitle/*, Style::Titlebar|Style::Close, WindowSettings(24,8,2)*/);
    pApp->Create(VideoMode(iWidth, iHeight, iBits), sTitle/*, Style::Titlebar|Style::Close, WindowSettings(24,8,2)*/);
    this->fTimeStep = m_fTimeStep;

    /****************/
        test.SetImage(*jfw::Image::Get("figure-1.tga"));
        std::cout<<"sprite works!"<<std::endl;
    /***************/
    return true;
}

void jfw::Engine::Run()
{
    float fAccumulator=0.0f;
    float fElapsedTime=0.0f;

    #ifdef DEBUG
        std::cout<<"Runned1"<<std::endl;
        std::cout<<fTimeStep<<std::endl;
    #endif

    while(/*App.IsOpened()*/pApp->IsOpened())
    {
        fElapsedTime  = Clock.GetElapsedTime();
        Clock.Reset();
        fElapsedTime = jfw::math::max(0.0f,fElapsedTime);

        fAccumulator += fElapsedTime;
        fAccumulator  = jfw::math::clamp(fAccumulator, 0.0f, 1.0f); //

        while (fAccumulator > fTimeStep)
        {
            Update(fTimeStep);
            fAccumulator -= fTimeStep;
        }

        Draw();
    }
}


void jfw::Engine::Update(float m_fDeltaTime)
{
    while(pApp->GetEvent(Event))
    {
        if (Event.Type == Event::Closed || Event.Key.Code == Key::Escape)
        {
            this->Close();
        }
    }

    jfw::GameObject::UpdateAll(m_fDeltaTime);

}

void jfw::Engine::Draw()
{
    pApp->Clear();
    jfw::GameObject::DrawAll();
    jfw::Player::DrawAll();
    pApp->Display();
}

void jfw::Engine::Close()
{
    if(pApp)
    {
        pApp->Close();
        delete pApp;
    }

}

jfw::Engine::~Engine()
{
}

